package com.hzp.controller;

import com.hzp.entity.Dept;
import com.hzp.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private DeptService deptService;

    @GetMapping("/list")
    public List<Dept> listDept(){
        return deptService.listDept();
    }

    @GetMapping("/get/{id}")
    @HystrixCommand(fallbackMethod = "processHystrix")
    public Dept getDept(@PathVariable("id") Integer id){
        Dept dept = deptService.getDept(id);

        if(dept==null){
            throw new RuntimeException("该ID" + id + "没有对应的数据");
        }
        return dept;
    }

    public Dept processHystrix(@PathVariable("id") Integer id){
        Dept dept = new Dept().setDeptno(id)
                .setDname("该ID" + id + "没有对应的数据")
                .setDbSource("mysql中没有对应数据");
        return dept;
    }

    @PostMapping("/add")
    public boolean addDept(@RequestBody Dept dept){
        return deptService.addDept(dept);
    }

    @GetMapping("/get/timeout")
    public String getTimeout(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "ok";
    }
}
